class EEGFatigueCalculator {
    constructor(sampleRate = 50) {
        if (!Number.isFinite(sampleRate) || sampleRate <= 0) {
            throw new Error('采样率必须为正数');
        }
        this.sampleRate = sampleRate;
        this.buffer = [];
        this.bufferSize = 1 * sampleRate;
        this.meanbuffer = [];
        this.meanBufferSize = 10;

        // 初始化滤波器配置
        this.filters = {
            delta: this.initializeFilter(0.5, 4),
            theta: this.initializeFilter(4, 8),
            alpha: this.initializeFilter(8, 13),
            beta: this.initializeFilter(13, 30)
        };
    }

    // 初始化滤波器系数和状态
    initializeFilter(lowFreq, highFreq) {
        const coefficients = this.getButterworthCoefficients(lowFreq, highFreq);
        return {
            a: coefficients.a,
            b: coefficients.b,
            x: new Array(coefficients.b.length).fill(0), // 输入历史
            y: new Array(coefficients.a.length).fill(0)  // 输出历史
        };
    }

    // 计算巴特沃斯滤波器系数
    getButterworthCoefficients(lowFreq, highFreq) {
        // if (lowFreq >= highFreq || lowFreq <= 0 || highFreq >= this.sampleRate / 2) {
        //     throw new Error('无效的频率范围');
        // }
        const fs = this.sampleRate;
        const w1 = 2 * Math.PI * lowFreq / fs;
        const w2 = 2 * Math.PI * highFreq / fs;
        const bw = w2 - w1;
        const w0 = (w1 + w2) / 2;

        const alpha = Math.sin(bw) / (2 * 0.707);
        const cosw0 = Math.cos(w0);
        const a0 = 1 + alpha;

        if (a0 === 0) {
            throw new Error('无效的滤波器系数：a0 不能为零');
        }

        const b = [alpha / a0, 0, -alpha / a0];
        const a = [a0 / a0, -2 * cosw0 / a0, (1 - alpha) / a0];

        return { b, a };
    }

    // 应用滤波器
    applyFilter(filter, input) {
        // 更新输入历史
        filter.x.unshift(input);
        filter.x.pop();

        // 计算滤波器输出
        let output = 0;
        for (let i = 0; i < filter.b.length; i++) {
            output += filter.b[i] * filter.x[i];
        }
        for (let i = 1; i < filter.a.length; i++) {
            output -= filter.a[i] * filter.y[i - 1];
        }
        output /= filter.a[0];

        // 更新输出历史
        filter.y.unshift(output);
        filter.y.pop();

        return output;
    }


    // 处理 EEG 数据点
    addDataPoint(eeg) {
        // console.log(eeg)

        // if (!Number.isFinite(eeg) || Math.abs(eeg) > 1e6) {
        //     return -1;
        // }

        // console.log(eeg)
        // 对每个频段应用滤波
        const delta = this.applyFilter(this.filters.delta, eeg);
        const theta = this.applyFilter(this.filters.theta, eeg);
        const alpha = this.applyFilter(this.filters.alpha, eeg);
        const beta = this.applyFilter(this.filters.beta, eeg);
        const power = delta * delta + theta * theta + alpha * alpha + beta * beta;

        // 存储到缓冲区
        this.buffer.push({ delta, theta, alpha, beta, power });
        // console.log(this.buffer.length)
        // 当缓冲区满时计算疲劳度
        if (this.buffer.length === this.bufferSize) {
            let sumDeltaEnergy = 0, sumThetaEnergy = 0, sumAlphaEnergy = 0, sumBetaEnergy = 0;
            for (let data of this.buffer) {
                sumDeltaEnergy += data.delta * data.delta;
                sumThetaEnergy += data.theta * data.theta;
                sumAlphaEnergy += data.alpha * data.alpha;
                sumBetaEnergy += data.beta * data.beta;
            }

            const meanDeltaEnergy = sumDeltaEnergy / this.bufferSize;
            const meanThetaEnergy = sumThetaEnergy / this.bufferSize;
            const meanAlphaEnergy = sumAlphaEnergy / this.bufferSize;
            const meanBetaEnergy = sumBetaEnergy / this.bufferSize;

            const denominator = meanAlphaEnergy + meanBetaEnergy;
            const powerRatio = denominator > 0 ? (meanDeltaEnergy + meanThetaEnergy) / denominator : 0;

            const maxPowerRatio = 10;
            const fatigue = Math.min(10, (powerRatio / maxPowerRatio) * 100);
            // console.log(fatigue)
            this.buffer = [];

            this.meanbuffer.push(fatigue);
            if (this.meanbuffer.length === this.meanBufferSize) {
                let sumFatigure = 0;
                for (let data of this.meanbuffer) {
                    sumFatigure += data;
                }
                const meanFatigue = sumFatigure / this.meanBufferSize;
                // console.log(sumFatigure)
                this.meanbuffer.shift();

                // console.log(this.meanbuffer.length)
                return Math.min(60, Math.max(0, Math.round(meanFatigue)));

            }
            return -1;
        }

        return -1;
    }

    // 重置滤波器和缓冲区状态
    reset() {
        this.buffer = [];
        for (let filter of Object.values(this.filters)) {
            filter.x.fill(0);
            filter.y.fill(0);
        }
    }
}


export { EEGFatigueCalculator };

// // 生成模拟EEG数据的函数
// function generateSimulatedEEG(sampleRate = 250, duration = 1, amplitudes = { delta: 15, theta: 10, alpha: 8, beta: 5 }, noiseLevel = 5) {
//     const samples = Math.floor(sampleRate * duration);
//     const eegData = [];

//     for (let i = 0; i < samples; i++) {
//         const t = i / sampleRate;
//         // 各频段正弦波
//         const deltaWave = amplitudes.delta * Math.sin(2 * Math.PI * 2 * t); // 2Hz (Delta)
//         const thetaWave = amplitudes.theta * Math.sin(2 * Math.PI * 6 * t); // 6Hz (Theta)
//         const alphaWave = amplitudes.alpha * Math.sin(2 * Math.PI * 10 * t); // 10Hz (Alpha)
//         const betaWave = amplitudes.beta * Math.sin(2 * Math.PI * 20 * t); // 20Hz (Beta)
//         // 随机噪声
//         const noise = (Math.random() - 0.5) * 2 * noiseLevel;
//         // 合成EEG信号
//         const eeg = deltaWave + thetaWave + alphaWave + betaWave + noise;
//         eegData.push(eeg);
//     }

//     return eegData;
// }

// // 测试函数：生成EEG数据并调用疲劳计算
// function testFatigueWithSimulatedEEG() {
//     const calculator = new EEGFatigueCalculator(250); // 采样率250Hz
//     const duration = 100; // 80点/250Hz ≈ 0.32秒
//     const sampleRate = 250;

//     // 生成模拟EEG数据
//     const eegData = generateSimulatedEEG(sampleRate, duration,
//         { delta: 15, theta: 10, alpha: 8, beta: 5 }, // 幅度
//         5 // 噪声水平
//     );

//     // 逐个输入EEG数据并计算疲劳值
//     console.log(`Simulating EEG data for ${duration} seconds (${eegData.length} samples)`);
//     eegData.forEach((eeg, i) => {
//         // 计算时间戳（模拟实时）
//         const timestamp = new Date(Date.now() + i * (1000 / sampleRate)).toISOString();

//         // 输入数据并获取疲劳值
//         const fatigue = calculator.addDataPoint(eeg);

//         // 输出
//         console.log(`4114Data point ${i + 1}:`);
//         console.log(`  Timestamp: ${timestamp}`);
//         console.log(`  EEG: ${eeg.toFixed(2)} μV`);
//         console.log(`  Fatigue: ${fatigue}`);
//         console.log('---');
//     });
// }

// // 运行测试
// testFatigueWithSimulatedEEG();